<?php


namespace app\common\model;

use app\common\model\Common as CommonModel;

class Category extends CommonModel
{
    protected $pk = 'id';

    /**
     * index页面数据获取
     * */
    public function tableData($post,$field='*',$isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = 10;
        }

        $tableWhere = $this->tableWhere($post);
        $query      = $this
            ->field($field)
            ->where($tableWhere['where'])->whereOr($tableWhere['whereOr'])->order($tableWhere['order']);


        if ($isPage) {
            $list        = $query->paginate([
                'list_rows'=> $limit,//每页数量
                'query' => request()->param(),
            ]);
            $data        = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $page = $list->render();
            $re['count'] = $list->total();
        } else {
            $list        = $query->select();
            $data        = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
            $page = [];
        }

        $re['code'] = 1;
        $re['msg']  = '';
        $re['data'] = $data;
        $re['page'] = $page;
        return $re;
    }


    protected function tableWhere($post)
    {
        $where = $whereOr = [];
        if(isset($post['parentid'])){
            $where[] = ['parentid','=',$post['parentid']];
        }
        if(isset($post['type']) && !empty($post['type'])){
            $where[] = ['type','=',$post['type']];
        }
        if(isset($post['title']) && !empty($post['title'])){
            $where[] = ['title','=',$post['title']];
        }
        if(isset($post['cate_id']) && !empty($post['cate_id'])){
            $where[] = ['cate_id','=',$post['cate_id']];
        }
        if(isset($post['is_open']) && !empty($post['is_open'])){
            $where[] = ['is_open','=',$post['is_open']];
        }
        $result['where']   = $where;
        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $pk = $this->pk;
        $result['order'] = ['orderid'=>'asc',$pk => 'desc'];
        return $result;
    }

    protected function tableFormat($list)
    {
        foreach($list as $k=>$v){
            $list[$k]['add_time'] = date("Y-m-d",$v['add_time']);
            //子集
            $list[$k]['arrchildid'] = getChildId($v['id']);

        }
        return $list;
    }


    public function handle($param){
        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];
        $act = $param['act'];

        $data['siteid'] = ADMIN_SITEID;
        $data['moduleid'] = $param['moduleid'];
        //模型名称
        $Module = new Module();
        $module_one = $Module -> where("id","=",$param['moduleid'])->find();
        $data['module'] = $module_one['name'];

        $data['parentid'] = isset($param['parentid'])?$param['parentid']:0;
        if($data['parentid']){
            $m_catdir =  $this -> where('id',$data['parentid'])->find();
            $data['arrparentid'] = $m_catdir['arrparentid'].','.$data['parentid'];
        }else{
            $data['arrparentid'] = 0;
        }
        $data['catname'] = isset($param['catname'])?$param['catname']:'';
        $data['catname1'] = isset($param['catname1'])?$param['catname1']:'';
        $data['url'] = isset($param['url'])?$param['url']:'';
        if(!empty($param['picurl'])){
            $data['picurl'] = implode(',',$param['picurl']);
        }else{
            $data['picurl'] = '';
        }
        if(!empty($param['picurl2'])){
            $data['picurl2'] = implode(',',$param['picurl2']);
        }else{
            $data['picurl2'] = '';
        }
        $data['title'] = isset($param['title'])?$param['title']:'';
        $data['keywords'] = isset($param['keywords'])?$param['keywords']:'';
        $data['description'] = isset($param['description'])?$param['description']:'';
        $data['template_list'] = isset($param['template_list'])?$param['template_list']:'';
        $data['template_show'] = isset($param['template_show'])?$param['template_show']:'';
        $data['pagesize'] = isset($param['pagesize'])?$param['pagesize']:10;
        $data['is_open'] = isset($param['is_open'])?$param['is_open']:1;
        $data['orderid'] = isset($param['orderid'])?$param['orderid']:1;
        $data['htmlname'] = isset($param['htmlname'])?$param['htmlname']:'';

        if($act == 'add'){
            $data['add_time'] = time();
            $r = $this->insertGetId($data);
            $id = $r;
            $ty = '添加';
        }
        if($act == 'edit'){
            $data['update_time'] = time();
            $r = $this->where('id','=',$param['id'])->update($data);
            $id = $param['id'];
            $ty = '修改';
        }
        if(!$r){
            $result['msg'] = '操作失败';
            return $result;
        }
        adminLog($data['catname'].'栏目'.$ty,$id);
        $result['code'] = 1;
        $result['msg'] = '操作成功';
        return $result;
    }


    //树形无限极结构
    public function menulist($menu,$id=0,$level=0){
        static $menus = array();
        foreach ($menu as $value) {
            if ($value['parentid']==$id) {
                $value['level'] = $level+1;
                if($level == 0)
                {
                    $value['str'] = '';
                }
                elseif($level == 2)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;'.'└ ';
                }
                elseif($level == 3)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;'.'└ ';
                }
                else
                {
                    $value['str'] = '&emsp;&emsp;'.'└ ';
                }
                $menus[] = $value;
                $this->menulist($menu,$value['id'],$value['level']);
            }
        }
        return $menus;
    }

    //树形结构(用于后台 筛选时)
    public function treeList($search,$is_false=true,$map=[],$catids=''){
//        $module_arr = [
//            'info'=>'单页模型',
//            'notice'=>'公告模型',
//            'policy'=>'政策法规模型',
//            'lists'=>'培训/职称模型',
//            'test1'=>'测试1',
//        ];
        $Module = new Module();
        $where = [];
        if($is_false){
            $where['is_open'] = ['=',1];
        }

        if(!empty($map)){
            $where['siteid'] = ['=',$map['siteid']];
        }

        if(!empty($search)){
            $right_list = $this->where($search)->where($where)->order('orderid asc')->select()->toArray();
            foreach($right_list as $k=>$v){
//                $right_list[$k]['module_name'] = $module_arr[$v['module']].'['.$v['module'].']';
//                $right_list[$k]['module_url'] = url($v['module'].'/list',['cate_id'=>$v['id']]);
            }
        }else{
            $right_list = $this->where($where)->order('orderid asc')->select()->toArray();
            $right_list = $this->menulist($right_list,0,0);

            foreach($right_list as $k=>$v){
                $right_list[$k]['catname'] = $v['str'].$v['catname'];
                $module_one = $Module->where("id","=",$v['moduleid'])->find();
//                $right_list[$k]['module_name'] = $module_one['title'].'['.$v['module'].']';
                $right_list[$k]['module_url'] = url($v['module'].'/list',['catid'=>$v['id']]);
                if($catids){
                    $field_arr = explode(",",$catids);
                    if(in_array($v['id'],$field_arr)){
                        $right_list[$k]['selected'] = 'true';
                    }else{
                        $right_list[$k]['selected'] = 'false';
                    }
                }else{
                    $right_list[$k]['selected'] = 'false';
                }

                if($v['level'] == 1){
                    $right_list[$k]['disabled'] = 'true';
                }else if($v['level'] == 2){ //2级栏目下有栏目 就不能选择当前栏目
                    $child_cate = $this
                        -> where("parentid","=",$v['id'])
                        ->where("is_open","=",1)
                        ->count();
                    if($child_cate > 0) {
                        $right_list[$k]['disabled'] = 'true';
                    }else{
                        $right_list[$k]['disabled'] = 'false';
                    }
                }else{
                    $right_list[$k]['disabled'] = 'false';
                }

            }
        }
        return $right_list;
    }

    //获取栏目id下所有子集的数组
    public function getChildList($cate_id,$level=2){
        $field='id,catname,catname1,parentid,module,arrparentid,orderid,picurl,url,template_list,template_show,add_time';
        $list = $this->where('parentid','=',$cate_id)
            ->where('is_open','=',1)
            ->field($field)->order('orderid asc,id desc')->select();
        foreach($list as $k=>$v){
            //子集(包括自己)
            $list[$k]['arrchildid'] = getChildId($v['id'],true);
            $list[$k]['level'] = $level;
            $is_child = $this->where('parentid','=',$v['id'])
                ->where('is_open','=',1)->field($field)->order('orderid asc,id desc')->select();
            if($is_child){
                $level++;
                $list[$k]['child'] = $this->getChildList($v['id'],$level);
            }

        }
        return $list;
    }


}